package com.example.tcpLearn.tcp4;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 多客户端与服务端通信：客户端
 */
public class Client {
    public static void main(String[] args) throws IOException {

        System.out.println("客户端启动...");

        Socket socket = new Socket("127.0.0.1", 8888);

        OutputStream outputStream = socket.getOutputStream();
        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

        InputStream inputStream = socket.getInputStream();
        DataInputStream dataInputStream = new DataInputStream(inputStream);

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入要发送的数据：");
            String msg = scanner.nextLine();
            if ("exit".equals(msg)) {
                System.out.println("客户端退出...");
                break;
            }
            dataOutputStream.writeUTF(msg);
            dataOutputStream.flush();

            String echo = dataInputStream.readUTF();
            System.out.println("服务器端返回的数据：" + echo);
            System.out.println("=============================");
        }

        dataInputStream.close();
        dataOutputStream.close();
        socket.close();

    }
}
